package server;

import java.io.*;

public class minicatClassLoader extends ClassLoader {
    private String servletClass;

    public minicatClassLoader(String servletClass) {
        this.servletClass = servletClass;
    }

    @Override
    public Class<?> findClass(String name)  {
        try {
            String className = "server.LagouServlet";
            byte[] content = getContent(name);
            Class<?> aClass = defineClass(servletClass, content, 0, content.length);
            return aClass;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }
}
